import React, {useEffect, useState} from 'react'
import Banner from './components/banner'
import Info from './components/info'
import Lists from './components/lists'
import {Footer, MyNavBar} from '@/components'
import {useDetailHook, useListHook} from '@/hooks'
import {history} from 'umi'
import {ActivityIndicator, Toast} from 'antd-mobile'

import './index.less'
import {
  _getHouseDetail,
  _getCommentReplyList,
  _postReply,
  _isCollection,
  _postCollection,
  _delCollection, _isOrder
} from './store'
import {queryString} from '@/utils'

export default function (props) {
  const id = queryString('id')

  const [isComment,setIsComment] = useState(false)

  if (!id) {
    Toast.fail('参数不正确')
    history.goBack()
  }

  let handleSearch1 = null

  const searchFunc1 = (onSearch) => {
    handleSearch1 = onSearch
  }

  const {detailData, loading} = useDetailHook({func: _getHouseDetail.bind(null, +id)})

  const {detailData: isCollection} = useDetailHook({func: _isCollection.bind(null, +id), searchFunc: searchFunc1})

  let handleSearch = null

  const searchFunc = (onSearch) => {
    handleSearch = onSearch
  }

  const {data: reply, loading: replyLoading} = useListHook({func: _getCommentReplyList.bind(null, id), searchFunc})

  const postReply = async (content, rid) => {
    let temp = {}
    if (typeof rid === 'number') {
      temp = {
        content, rid
      }
    } else {
      temp = {
        content,
        houseId: id
      }
    }
    const result = await _postReply(temp)
    if (result) {
      handleSearch()
      Toast.success('评论成功,请等待审核')
    }
  }

  const handleClick = async (status,id) => {
    let result = null
    if(status) {
      result = await _postCollection(id)
    } else {
      result = await _delCollection(id)
    }
    if(result) {
      handleSearch1()
      Toast.success('操作成功')
    }
  }

  const isShouldComment = async ()=>{
    const data=await _isOrder(id)
    setIsComment(!!data.flag)
  }

  useEffect(()=>{
    isShouldComment()
  },[])

  return (
    <div className='house-page'>
      <MyNavBar title='民宿查看'/>
      {loading ? <ActivityIndicator toast/> :
        <div>
          <Banner
            pictures={detailData?.houseInfo?.pictures ? detailData.houseInfo.pictures.split('|') : [ require('@/assets/blank.png') ]}/>
          <Info handleClick={handleClick} isCollection={isCollection?.flag} detail={detailData}/>
        </div>
      }

      {<Lists lists={reply} showLoading={replyLoading}/>}}
      {isComment && <Footer postReply={postReply}/>}
    </div>
  )
}
